package com.lmt.service.impl;

import com.lmt.base.BaseService;
import com.lmt.base.ResultData;
import com.lmt.entity.Audit;
import com.lmt.entity.ResourceTemp;
import com.lmt.entity.search.AuditSearch;
import com.lmt.repository.AuditRepository;
import com.lmt.service.AuditService;
import com.lmt.service.ResourceService;
import com.lmt.util.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import java.util.List;
import java.util.Map;

/**
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@Service("AuditServiceImpl")
public class AuditServiceImpl extends BaseService implements AuditService {

	private final AuditRepository auditRepository;

	private final ResourceService resourceService;

	private final RedisCacheUtil redisCacheUtil;

	@Autowired
	public AuditServiceImpl(AuditRepository auditRepository, ResourceService resourceService,
                            RedisCacheUtil redisCacheUtil) {
		this.auditRepository = auditRepository;
		this.resourceService = resourceService;
		this.redisCacheUtil = redisCacheUtil;
	}


	@Override
	public ResultData save(Audit audit) {
		Audit exist = this.auditRepository.findByObjIdAndOperation(audit.getObjId(), audit.getOperation());
		if (null != exist) {
			return ResultUtil.newSuccess("该资源的审核操作记录已存在");
		}
		this.auditRepository.save(audit);
		if (null == audit.getId()) {
			return ResultUtil.newFail("审核数据保存失败");
		}
		return ResultUtil.newSuccess("审核数据保存成功");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResultData update(Audit audit) {
		List<ResourceTemp> resourceTemps = audit.getResourceTemps();
		// 处理审核记录信息
		for (ResourceTemp resourceTemp : resourceTemps) {
			Audit exist = this.auditRepository.findByObjIdAndStatusEquals(resourceTemp.getId(),
					SystemConstant.AUDIT_STATUS_WAIT);
			if (null == exist) {
				return ResultUtil.newFail("该待审核资源 [ID = " + resourceTemp.getId() + "] 的待审核记录不存在");
			}
			Audit updateAudit = new Audit();
			updateAudit.setStatus(audit.getStatus());
			updateAudit.setRemark(audit.getRemark());
			updateAudit.setAuditorId(redisCacheUtil.getUserId(audit));
			BeanUtils.copyProperties(updateAudit, exist, EntityUtils.getNullPropertyNames(updateAudit));
			entityManager.merge(exist);
			this.auditRepository.save(exist);
		}
		// 审核通过，处理资源信息
		if (SystemConstant.AUDIT_STATUS_PASS.equals(audit.getStatus())) {
			ResultData result = this.handleSystemResource(audit.getResourceTemps(), audit.getRemark());
			if (CheckResult.isFail(result)) {
				return result;
			}
		}
		return ResultUtil.newSuccess("审核成功");
	}

	@Override
	public ResultData search(AuditSearch auditSearch) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT a.remark, ");
		sql.append("a.gmt_modified AS gmtModified, ");
		sql.append("a.gmt_create AS gmtCreate, ");
		sql.append("rt.designation AS resourceTempDesignation, ");
		sql.append("(SELECT ui.user_name FROM user_info AS ui WHERE ui.id = a.auditor_id) ");
		sql.append("AS auditor, ");
		sql.append("(SELECT dd.designation FROM digital_dictionary AS dd WHERE dd.code = a.operation) ");
		sql.append("AS operation, ");
		sql.append("(SELECT dd.designation FROM digital_dictionary AS dd WHERE dd.code = a.status) ");
		sql.append("AS status ");
		sql.append("FROM audit AS a, resource_temp AS rt WHERE rt.id = a.obj_id ");
		if (!StringUtils.isEmpty(auditSearch.getKeyword())) {
			sql.append("AND (a.remark LIKE ? OR rt.designation LIKE ? ) ");
			auditSearch.setParamsCount(2);
		}
		Map result = this.paginationSearch(sql, auditSearch);
		return ResultUtil.newSuccess("审核记录查询成功", result);
	}

	/**
	 * 处理资源表
	 * @param resourceTemps 待审核资源数据
	 * @param auditRemark 审核备注
	 * @return ResultData
	 */
	private ResultData handleSystemResource(List<ResourceTemp> resourceTemps, String auditRemark) {
		for (ResourceTemp resourceTemp : resourceTemps) {
			ResultData result = null;
			if (SystemConstant.AUDIT_OPERATION_ADD.equals(resourceTemp.getOperationCode())) {
				// 新增资源通过审核
				result = this.resourceService.addResourceFromResourceTemp(resourceTemp, auditRemark);
			}
			if (SystemConstant.AUDIT_OPERATION_DELETE.equals(resourceTemp.getOperationCode())) {
				// 删除资源通过审核
				result = this.deleteSystemResource(resourceTemp);
			}
			if (CheckResult.isFail(result)) {
				return result;
			}
		}
		return ResultUtil.newSuccess("资源数据处理成功");
	}

	/**
	 * 删除资源
	 * @param resourceTemp 要删除的资源对应的待审核资源信息
	 * @return ResultData TODO 删除资源
	 */
	private ResultData deleteSystemResource(ResourceTemp resourceTemp) {
		return null;
	}

}
